//
//  UIImageView+Gif.m
//  boot
//
//  Created by Demi on 14/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "UIImageView+Gif.h"

#import "UIImage+Gif.h"

#import <objc/runtime.h>

#import <ReactiveObjC/ReactiveObjC.h>

@implementation UIImageView (Gif)

#pragma mark - one-time animation.

- (void)startAnimatingWithImages:(NSArray<UIImage *> *)images duration:(NSTimeInterval)ti completion:(void (^)(void))completion
{
    NSTimeInterval interval = ti / (double)images.count;
    [self animatedImages:[NSMutableArray arrayWithArray:images] interval:interval completion:completion];
}

- (void)animatedImages:(NSMutableArray<UIImage *> *)images interval:(NSTimeInterval)interval completion:(void(^)(void))completion
{
    if (images.count > 0)
    {
        self.image = images.firstObject;
        [images removeObjectAtIndex:0];
    }
    else
    {
        completion();
        return;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self animatedImages:images interval:interval completion:completion];
    });
}

@end
